package com.lx.spring.mvc.web;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConvertor implements Converter<String, Date> {

    SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat yyyyMMdd1 = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat yyyyMMdd2 = new SimpleDateFormat("yyyy年MM月dd日");

    @Override
    public Date convert(String source) {
        if(source == null || source.isBlank()) return null;
        source = source.trim();
        if(source.length() == "yyyy-MM-dd".length()){
            return parse(yyyyMMdd1, source);
        }else if(source.length() == "yyyy年MM月dd日".length()){
            return parse(yyyyMMdd2, source);
        }else if(source.length() == "yyyy-MM-dd HH:mm:ss".length()){
            return parse(yyyyMMddHHmmss, source);
        }
        return null;
    }

    private Date parse(SimpleDateFormat fmt, String source) {
        try {
            return fmt.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
}
